// //两数之和
// function twoSum(nums, target) {
//     let map = new Map();
//     for (let i = 0; i < nums.length; i++) {
//         let diff = target - nums[i];
//         if (map.has(diff)) {  //如果map中有diff，则返回结果    如果map中没有diff，则把当前值和索引放入map中
//             return [map.get(diff), i];
//         }
//         map.set(nums[i], i);
//     }
// }
// twoSum([2, 7, 11, 15], 9);
// console.log(twoSum([2, 7, 11, 15], 9));
// }
// var twoSum = function(nums, target) {
//     // let newTarget = target - nums[i];
//     let n = nums.length;
//     for (let i = 0; i < n; i++){
//         if(nums[i] > target)
//     }
//
// };

//两数之和用到什么算法    哈希表 双指针 排序

// function twoSum(nums, target) {
//     let map = new Map();
//     for (let i = 0; i < nums.length; i++){
//         if (map.has(target-nums[i]) === true) { // 如果map中有这个值，则返回
//             return [map.get(target-nums[i]), i] //返回两个数的索引
//         }
//         //为什么这一步不能写在上面，因为map.get(target-nums[i])可能返回undefined
//         map.set(nums[i],i)//把当前的值和下标存入map
//     }
// }
// console.log(twoSum([2, 7, 11, 15], 9));

function twoSum(nums, target) {
    let n = nums.length;
    let map = new Map();
    for (let i = 0; i < n; i++) {
        let diff = target - nums[i];
        if (map.has(diff)) {
            return [map.get(diff), i]; //set(diff, map.get(diff) + 1);
        }
        map.set(nums[i], i);
    }
}
console.log(twoSum([2, 7, 11, 15], 9));